<?php
class SettingsController extends AppController {

	var $name = 'Settings';

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->deny('index');
	}


	function index() {
		$data = false;
		$uid = $this->Auth->user('id');
#pr ($this->data);

		if ($uid) {
			$this->loadModel('Privacy');
			$this->loadModel('SearchOption');
			$this->loadModel('SearchRelation');

			if (isset($this->data['SearchOption'])) {

				$soData =  $this->data['SearchOption'];

				if ($id = $this->SearchOption->getSearchOptionID($uid)) {
					$this->SearchOption->id = $id;
					$this->SearchOption->saveSearchOptions($soData);
				}

			}
			
			if (isset($this->data['SearchRelation'])) {
				$srData = $this->data['SearchRelation'];
				
				if ($id = $this->SearchRelation->getSearchRelationID($uid)) {
					$this->SearchRelation->id = $id;
					$this->SearchRelation->saveSearchRelation($srData);
				}
			}

			if (isset($this->data['Privacy'])) {
				$id = $this->Privacy->getSettingID($uid);
				if ($id) {
					$this->Privacy->id = $id;
					$this->Privacy->save($this->data);
				}
			}



			if (isset($this->data['User'])) {
				$passtrue = false;
				$this->loadModel('User');
				$this->User->set($this->data);

				$pass = $this->Auth->password($this->data['User']['password']);

				if ($this->User->checkPass($uid, $pass)) {
					$passtrue = 1;
				} else {
					$this->User->invalidate('password', 'wrong');
				}

				if ($this->User->validates()) {
					if ($passtrue) {
						$newpass = $this->Auth->password($this->data['User']['repassword']);
						$this->User->id = $uid;
						if ($this->User->saveField('passwd', $newpass)) {
							$this->Session->setFlash('Пароль изменен');
							unset($this->data['User']);
						}
					}
				}
			}


			$this->loadModel('UsersSoctype');
			if (isset($this->data['Account'])) {
				$status = intval($this->data['Account']['status']);
				$this->UsersSoctype->changeStatus($uid, $status);
			}

			if (!isset($this->data)) {
				$this->data = array();
			}

			if ($socType = $this->UsersSoctype->getSoctype($uid)) {
				$this->data = array_merge($this->data, $socType);
			}
			$this->data = array_merge($this->data, $this->Privacy->getData($uid));
			$this->data = array_merge($this->data, $this->SearchOption->getData($uid));
			$this->data = array_merge($this->data, $this->SearchRelation->getData($uid));
		}

		$this->loadModel('Socrelation');
		$data['relations'] = $this->Socrelation->getRelations(array('limit'=>7));

		if ($data) {
			$this->set($data);
		}
	}

}
?>
